// src/shared/utils/init.ts

import { STORAGE_KEYS, hasStorageData, setStorageData, clearAllMallData } from './storage';
import { loadAllInitialData } from './dataLoader';

/**
 * 初始化应用数据
 * 检查localStorage是否有数据，如果没有则从JSON文件加载初始数据
 */
export const initializeData = async (): Promise<void> => {
  try {
    console.log('开始初始化商城数据...');

    // 检查是否已经有数据（以用户数据为标准）
    if (hasStorageData(STORAGE_KEYS.USERS)) {
      console.log('检测到已有数据，跳过初始化');
      return;
    }

    console.log('首次访问，开始加载初始数据...');

    // 加载所有初始数据
    const data = await loadAllInitialData();

    // 写入localStorage
    setStorageData(STORAGE_KEYS.USERS, data.users);
    setStorageData(STORAGE_KEYS.PRODUCTS, data.products);
    setStorageData(STORAGE_KEYS.HOT_PRODUCTS, data.hotProducts);
    setStorageData(STORAGE_KEYS.CATEGORIES, data.categories);
    setStorageData(STORAGE_KEYS.ORDERS, data.orders);
    setStorageData(STORAGE_KEYS.ORDER_ITEMS, data.orderItems);
    setStorageData(STORAGE_KEYS.CART_ITEMS, data.cartItems);
    setStorageData(STORAGE_KEYS.ADDRESSES, data.addresses);
    setStorageData(STORAGE_KEYS.BANNERS, data.banners);

    console.log('初始数据加载完成！');
    console.log('数据统计:', {
      users: data.users.length,
      products: data.products.length,
      hotProducts: data.hotProducts.length,
      categories: data.categories.length,
      orders: data.orders.length,
      orderItems: data.orderItems.length,
      cartItems: data.cartItems.length,
      addresses: data.addresses.length,
      banners: data.banners.length
    });

  } catch (error) {
    console.error('初始化数据失败:', error);
    throw new Error('应用初始化失败，请刷新页面重试');
  }
};

/**
 * 重置所有数据
 * 清空localStorage并重新加载初始数据
 */
export const resetAllData = async (): Promise<void> => {
  try {
    console.log('开始重置所有数据...');

    // 清空localStorage
    clearAllMallData();

    // 重新初始化
    await initializeData();

    console.log('数据重置完成！');
  } catch (error) {
    console.error('重置数据失败:', error);
    throw new Error('数据重置失败');
  }
};

/**
 * 检查数据完整性
 * 验证localStorage中是否包含所有必需的数据
 */
export const checkDataIntegrity = (): boolean => {
  const requiredKeys = [
    STORAGE_KEYS.USERS,
    STORAGE_KEYS.PRODUCTS,
    STORAGE_KEYS.CATEGORIES,
    STORAGE_KEYS.BANNERS
  ];

  return requiredKeys.every(key => hasStorageData(key));
};

/**
 * 获取数据统计信息
 */
export const getDataStats = () => {
  return {
    hasUsers: hasStorageData(STORAGE_KEYS.USERS),
    hasProducts: hasStorageData(STORAGE_KEYS.PRODUCTS),
    hasHotProducts: hasStorageData(STORAGE_KEYS.HOT_PRODUCTS),
    hasCategories: hasStorageData(STORAGE_KEYS.CATEGORIES),
    hasOrders: hasStorageData(STORAGE_KEYS.ORDERS),
    hasOrderItems: hasStorageData(STORAGE_KEYS.ORDER_ITEMS),
    hasCartItems: hasStorageData(STORAGE_KEYS.CART_ITEMS),
    hasAddresses: hasStorageData(STORAGE_KEYS.ADDRESSES),
    hasBanners: hasStorageData(STORAGE_KEYS.BANNERS),
    hasCurrentUser: hasStorageData(STORAGE_KEYS.CURRENT_USER)
  };
};